package it.polimi.swKnights.SWIMv2.general;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;

public class FileImageManager
{

	private BufferedImage image;
	
	public FileImageManager(File file) throws IllegalArgumentException
	{
		if(isImage(file))
		{
			this.image = this.fromFileToImage(file);
		}
		else
			throw new IllegalArgumentException();
	}
	
	public BufferedImage resizeImage(int width, int height)
	{
		
		BufferedImage resizedImage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = resizedImage.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.drawImage(image, 0, 0, width, height, null);
		g.dispose();
		
		return resizedImage;

	}

	public byte[] getByteFromImage()
	{

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] imageInByte = null;

		try
		{
			ImageIO.write(image, "jpg", baos);
			baos.flush();
			imageInByte = baos.toByteArray();
			baos.close();
		}
		catch (IOException e)
		{

			e.printStackTrace();
		}

		return imageInByte;
	}

	/**
	 * reference to ImageIO.read(File f) javadoc Returns a BufferedImage as the
	 * result of decoding a supplied File with an ImageReader chosen
	 * automatically from among those currently registered. The File is wrapped
	 * in an ImageInputStream. If no registered ImageReader claims to be able to
	 * read the resulting stream, null is returned.
	 */
	private BufferedImage fromFileToImage(File file)
	{
	
		BufferedImage img = null;
		try
		{
			img = ImageIO.read(file);
		}
		catch (IOException e)
		{
		}
	
		return img;
	}

	private boolean isImage(File file)
	{
		String mimeType = new MimetypesFileTypeMap().getContentType(file);
		String type = mimeType.split("/")[0];
	
		if (type.equals("image"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

}
